//! 指令模块
//! 
//! 支持多种架构的指令编码
//! 当前支持：8086 (16位)

mod arch_8086;

use crate::ast::Instruction;

// 架构抽象（未来扩展）
pub trait InstructionEncoder {
    fn encode_instruction(
        &self,
        instruction: &str,
        operands: &[crate::ast::Operand],
    ) -> crate::error::Result<Vec<u8>>;
    
    /// 估算指令大小（用于第一遍扫描）
    fn estimate_instruction_size(
        &self,
        instruction: &Instruction,
    ) -> crate::error::Result<usize>;
    
    /// 获取跳转指令的偏移范围 (min, max)
    fn get_jump_offset_range(
        &self,
        instruction: &str,
    ) -> Option<(i64, i64)>;
    
    /// 获取地址大小（字节数）
    fn address_size(&self) -> usize;
    
    /// 检查是否为条件跳转指令
    fn is_conditional_jump(&self, name: &str) -> bool;
}

// 架构枚举
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Architecture {
    I8086,
    // I80386,  // 未来支持
    // X64,     // 未来支持
}

impl Architecture {
    /// 获取架构的显示名称
    pub fn display_name(&self) -> &'static str {
        match self {
            Architecture::I8086 => "8086 (16位)",
            // Architecture::I80386 => "80386 (32位)",
            // Architecture::X64 => "x64 (64位)",
        }
    }
    
    /// 从字符串解析架构
    pub fn from_str(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "8086" | "i8086" => Some(Architecture::I8086),
            // "80386" | "i386" | "386" => Some(Architecture::I80386),
            // "x64" | "x86_64" | "amd64" => Some(Architecture::X64),
            _ => None,
        }
    }
}

// 根据架构创建编码器
pub fn create_encoder(arch: Architecture) -> Box<dyn InstructionEncoder> {
    match arch {
        Architecture::I8086 => Box::new(arch_8086::Encoder8086::new()),
        // Architecture::I80386 => todo!("80386 支持"),
        // Architecture::X64 => todo!("x64 支持"),
    }
}

// 默认导出 8086（保持向后兼容）
pub use arch_8086::Encoder8086;
pub use arch_8086::RegisterEncoding;

